import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { NavBar, Toast } from 'antd-mobile'
import styles from './Chooseschool.module.css'
import { LeftOutline } from 'antd-mobile-icons'
import axios from "axios"
import  {http,host,port} from '../utils/host'

// 定义学校数据接口，注意使用MongoDB的_id作为唯一标识
interface University {
    _id: string;
    name: string;
    abbreviation: string;
}

const Chooseschool: React.FC = () => {
    const [showUniversityList, setShowUniversityList] = useState<boolean>(false);
    const [universities, setUniversities] = useState<University[]>([]);
    const [loading, setLoading] = useState<boolean>(true);
    const [isSelecting, setIsSelecting] = useState<boolean>(false);
    const [selectedUniversity, setSelectedUniversity] = useState<University | null>(null);
    const navigate = useNavigate();

    // 从后端API获取学校列表数据
    const getSchools = async () => {
        try {
            setLoading(true);
            const res = await axios.get(`${http}${host}${port}/school`);
            console.log('获取到的学校数据:', res.data.data);
            setUniversities(res.data.data);
        } catch (error) {
            console.error('获取学校数据失败:', error);
            Toast.show({
                content: '获取学校数据失败，请重试',
                position: 'center',
            });
        } finally {
            setLoading(false);
        }
    }
    
    useEffect(() => {
        getSchools();
        // 页面加载后自动显示大学列表
        const timer = setTimeout(() => {
            setShowUniversityList(true);
        }, 500);
        return () => clearTimeout(timer);
    }, [])

    // 按拼音首字母排序
    const sortedUniversities = universities.sort((a, b) => {
        const pinyinA = getPinyin(a.name);
        const pinyinB = getPinyin(b.name);
        return pinyinA.localeCompare(pinyinB);
    });

    // 简单的拼音转换函数（实际项目中建议使用pinyin等专业库）
    function getPinyin(chinese: string): string {
        const pinyinMap: { [key: string]: string } = {
            '北': 'B', '大': 'D', '东': 'D', '电': 'D', '复': 'F', '哈': 'H', '华': 'H', '吉': 'J', '江': 'J', '兰': 'L',
            '南': 'N', '清': 'Q', '山': 'S', '上': 'S', '四': 'S', '天': 'T', '同': 'T', '武': 'W', '西': 'X', '厦': 'X',
            '浙': 'Z', '中': 'Z'
        };

        const firstChar = chinese.charAt(0);
        return pinyinMap[firstChar] || firstChar;
    }

    const handleUniversitySelect = (university: University) => {
        console.log('选择的大学:', university.name);
        setSelectedUniversity(university);
        setIsSelecting(true);
        setShowUniversityList(false);
        
        // 5秒后跳转到注册页面，并传递学校信息
        setTimeout(() => {
            setIsSelecting(false);
            navigate(`/register?schoolId=${university._id}&schoolName=${encodeURIComponent(university.name)}`);
        }, 5000);
    };
    
    const back = () => {
        navigate('/guide');
    };

    return (
        <div className={styles['chooseschool-container']}>
            {/* 装饰性背景元素 */}
            <div className={styles['background-decoration-1']} />
            <div className={styles['background-decoration-2']} />

            {/* 导航栏 */}
            <NavBar onBack={back} style={{ color: 'white' }}>选择学校</NavBar>

            {/* 主要内容区域 */}
            <div className={styles['main-content']}>
                <div className={styles['welcome-section']}>
                    <h1 className={styles['welcome-title']}>欢迎使用</h1>
                    <p className={styles['welcome-subtitle']}>请选择您的学校开始体验</p>
                </div>

                {/* 选择按钮 */}
                <button
                    className={styles['select-button']}
                    onClick={() => setShowUniversityList(true)}
                >
                    选择学校
                </button>
            </div>

            {/* 底部弹出层 */}
            {showUniversityList && (
                <div className={styles['popup-overlay']}>
                    {/* 弹出层头部 */}
                    <div className={styles['popup-header']}>
                        <span className={styles['popup-title']}>选择您的学校</span>
                        <button
                            className={styles['close-button']}
                            onClick={() => setShowUniversityList(false)}
                        >
                            ✕
                        </button>
                    </div>

                    {/* 大学列表 */}
                    <div className={styles['university-list']}>
                        {loading ? (
                            <div className={styles['loading']}>加载中...</div>
                        ) : universities.length > 0 ? (
                            sortedUniversities.map((university) => (
                                <div
                                    key={university._id}  // 使用数据库中的_id作为唯一标识
                                    className={styles['university-item']}
                                    onClick={() => handleUniversitySelect(university)}
                                >
                                    <div className={styles['university-info']}>
                                        <div className={styles['university-name']}>
                                            {university.name}
                                        </div>
                                        <div className={styles['university-abbreviation']}>
                                            {university.abbreviation}
                                        </div>
                                    </div>
                                    <div className={styles['university-arrow']}>›</div>
                                </div>
                            ))
                        ) : (
                            <div className={styles['no-data']}>暂无学校数据</div>
                        )}
                    </div>
                </div>
            )}

            {/* 遮罩层 */}
            {showUniversityList && (
                <div
                    className={styles['modal-backdrop']}
                    onClick={() => setShowUniversityList(false)}
                />
            )}

            {/* 选择加载效果 */}
            {isSelecting && (
                <div className={styles['selecting-overlay']}>
                    <div className={styles['selecting-content']}>
                        <div className={styles['loading-spinner']}></div>
                        <div className={styles['selecting-text']}>
                            正在为您配置 {selectedUniversity?.name} 的校园环境...
                        </div>
                        <div className={styles['selecting-subtitle']}>
                            请稍候，即将跳转到注册页面
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
};

export default Chooseschool;
